package com.sscl.baselibrary.exts

import androidx.annotation.IntRange


/**
 * LongExt
 *
 * Long扩展函数
 * @author jackie Penghe
 * @date 2024/9/4
 */



/**
 * 将Long类型转为字节数组
 */
fun Long?.toByteArray(): ByteArray? {
    this ?: return null
    val byteLength = 2
    var hexString: String = java.lang.Long.toHexString(this)
    val length: Int = hexString.length
    if (length % byteLength == 0) {
        val byteArray = ByteArray(length / byteLength)
        for (i in byteArray.indices) {
            val cacheString: String = hexString.substring(i * byteLength, i * byteLength + 2)
            val cache: Short = cacheString.toShort(16)
            byteArray[i] = cache.toByte()
        }
        return byteArray
    } else {
        val byteArray = ByteArray(length / byteLength + 1)
        val substring: String = hexString.substring(0, 1)
        byteArray[0] = substring.toShort(16).toByte()
        hexString = hexString.substring(1)
        for (i in 0 until byteArray.size - 1) {
            val cacheString: String = hexString.substring(i * byteLength, i * byteLength + 2)
            val cache: Short = cacheString.toShort(16)
            byteArray[i + 1] = cache.toByte()
        }
        return byteArray
    }
}

/**
 * 将 long 类型数转为指定长度的 byte 数组
 *
 * @param byteArrayLength 指定的数组长度
 * @return byte 数组
 */
fun Long?.toByteArray(@IntRange(from = 1, to = 8) byteArrayLength: Int): ByteArray? {
    var bytes: ByteArray = toByteArray() ?: return null
    val length: Int = bytes.size
    if (length < byteArrayLength) {
        val index: Int = byteArrayLength - length
        val cache = ByteArray(byteArrayLength)
        System.arraycopy(bytes, 0, cache, index, length)
        bytes = ByteArray(byteArrayLength)
        System.arraycopy(cache, 0, bytes, 0, byteArrayLength)
    } else if (length > byteArrayLength) {
        val index: Int = length - byteArrayLength
        val cache = ByteArray(byteArrayLength)
        System.arraycopy(bytes, index, cache, 0, byteArrayLength)
        bytes = ByteArray(byteArrayLength)
        System.arraycopy(cache, 0, bytes, 0, cache.size)
    }
    return bytes
}